package com.qing.shirodemo.config;

import com.qing.shirodemo.entity.User;
import com.qing.shirodemo.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

//自定义Realm
public class UserRealm  extends AuthorizingRealm {


    @Autowired
    private UserService userService;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了==>授权doGetAuthorizationInfo");


        //拿到当前登录的这个对象
        Subject subject= SecurityUtils.getSubject();
        User user=(User) subject.getPrincipal();
        List<String> list= Arrays.asList(user.getPerms().split(","));
        //设置权限
        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
        //添加权限
        info.addStringPermissions(list);
        return info;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("执行了==>认证doGetAuthenticationInfo");

        //用户名，密码，数据库中获取
//        String name="root";
//        String password="123456";



        UsernamePasswordToken usernamePasswordToken=(UsernamePasswordToken) authenticationToken;

        //连接真实数据库
       User user= userService.findUser(usernamePasswordToken.getUsername());

       if(user==null){
            return null;
       }

       Subject subject=SecurityUtils.getSubject();
       Session session=subject.getSession();
       session.setAttribute("loginUser",user);

//        if(!usernamePasswordToken.getUsername().equals(name)){
//                return  null;//抛出异常  UnknownAccountException
//        }
        //密码认证，shiro做
        return new SimpleAuthenticationInfo(user,user.getPassword(),"");
    }
}
